package com.opennetexam.manager.interceptor;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * @author 奶茶
 * Created on 2017/11/2.
 */
@Aspect
@Component
public class ApiAspect {

    private Logger logger = Logger.getLogger(ApiAspect.class);

    @Pointcut("execution(public * com.opennetexam.manager.controller.*.*(..))")
    public void log(){}

    /**
     * 请求之前
     * 打印请求日志
     */
    @Before("log()")
    public void doBefore(JoinPoint joinPoint) throws IOException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //url + method
        logger.info(String.format("url={%s};method={%s}",request.getRequestURL(),joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()));

        String servletPath = request.getServletPath();
        if(!servletPath.contains("/404") && !servletPath.contains("/500") && !servletPath.contains("/druid") ){
            if(servletPath.contains("/Examinee/")){
                request.getSession().setAttribute("jumpurl","/Examinee/Login");
            }else {
                request.getSession().setAttribute("jumpurl","/Login/Index");
            }
        }

    }
}
